package cn.myjerry.test.JDBC;

import java.io.FileOutputStream;
import java.io.IOException;import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 测试BLOB 二进制大对象的使用
 * @author Jerry
 *
 */
public class Demo09 {
	// JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/testjdbc?useSSL=true&useUnicode=true&characterEncoding=utf8";
    
    // 数据库的用户名与密码，需要根据自己的设置
    static final String USER = "root";
    static final String PASS = "Jerry1912317";
	
	public static void main(String[] args) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		InputStream is = null;
		OutputStream os = null;
		// 加载驱动类
		try {
			Class.forName(JDBC_DRIVER);
			conn = DriverManager.getConnection(DB_URL, USER, PASS);
			
//			ps = conn.prepareStatement("UPDATE User SET HeadImg=? WHERE Id=3009");
//			ps.setBlob(1, new FileInputStream(new File("/Users/zpon/workspace/web/buy-www/images/1.png")));
//			ps.execute();
//			System.out.println("插入成功");
			
			ps = conn.prepareStatement("SELECT * FROM User WHERE Id = ?");
			ps.setInt(1, 3009);
			res = ps.executeQuery();
			while(res.next()) {
				Blob c = res.getBlob("HeadImg");
				is = c.getBinaryStream();
				os = new FileOutputStream("/Users/zpon/Desktop/111.png");
				int temp = 0;
				while((temp=is.read()) != -1) {
					os.write(temp);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(res != null) {
				try {
					res.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
